<template>
  <div class="triage-other">
    <el-row type="flex" justify="end" class="button-save">
      <el-button type="primary" @click="valid">保存</el-button>
    </el-row>
    <el-form
      ref="painScoreForm"
      :inline="false"
      :class="required == '1' ? 'require' : 'notRequire'"
      :model="painScore"
      label-position="right"
      label-width="120px"
      size="small"
      :rules="painScoreRules"
    >
      <el-form-item label="疼痛评分" prop="value">
        <el-col :span="12">
          <el-input v-model="painScore.score" readonly />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :span="1" class="textCenter">
          <strong style="vertical-align: sub">无痛</strong>
        </el-col>
        <el-col :span="15">
          <el-slider
            v-model="painScore.value"
            :step="1"
            :max="10"
            show-stops
            @input="painScoreGrade"
          />
        </el-col>
        <el-col :span="1" class="textCenter">
          <strong style="vertical-align: sub">剧痛</strong>
        </el-col>
      </el-form-item>
    </el-form>
    <el-row
      v-for="(item, index) in scoreList"
      :key="item.index + index"
      class="card"
    >
      <el-row class="card-title" type="flex">
        <el-col :sm="24" class="content"> {{ item.name }} </el-col>
      </el-row>
      <row
        v-if="!item.fieldType || item.fieldType != 'content'"
        :key="timer"
        :list="item.scoreClassList"
        :disabled="item.status == '0'"
        @dataEmit="getGradeSpan(item, index)"
      />
      <check
        v-if="!item.fieldType || item.fieldType != 'content'"
        v-model="item.data"
        :list="item.scoreClassList"
        style="padding-left: 30px"
        :disabled="item.status == '0'"
        @dataEmit="getGradeSpan(item, index)"
      />
      <el-row
        class="card-content card-content-result"
        style="padding-left: 0px"
        type="flex"
      >
        <div class="card-content-title" align="right">
          <span v-if="required && required != '2'" class="required">*</span>
          结果：
        </div>
        <div
          class="result-grade"
          :class="required == '1' ? 'require' : 'notRequire'"
        >
          <el-input v-model="item.grade" size="small" readonly />
        </div>
        <div class="result-score">
          <el-input v-model="item.mark" size="small" readonly />
        </div>
        <div class="card-content-title">分</div>
      </el-row>
    </el-row>
    <!-- <el-form
      :inline="false"
      :model="otherScores"
      label-position="right"
      label-width="120px"
      size="small"
    >
      <el-form-item label="GCS评分">
        <el-col :span="24">
          <el-col :span="12">
            <el-input v-model="otherScores.vals" placeholder="" />
          </el-col>
        </el-col>
        <el-col :span="2">
          <span>E 睁眼：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="无睁眼">无睁眼</el-radio>
            <el-radio label="疼痛刺激睁眼">疼痛刺激睁眼</el-radio>
            <el-radio label="语言刺激睁眼">语言刺激睁眼</el-radio>
            <el-radio label="自发睁眼">自发睁眼</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>V 语言：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="无发音">无发音</el-radio>
            <el-radio label="只能发育">只能发育</el-radio>
            <el-radio label="只能说（不适当）单词">
              只能说（不适当）单词
            </el-radio>
            <el-radio label="言语错乱">言语错乱</el-radio>
            <el-radio label="正常交谈">正常交谈</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>M 运动：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="无反应">无反应</el-radio>
            <el-radio label="异常伸展（去脑状态）">
              异常伸展（去脑状态）
            </el-radio>
            <el-radio label="异常屈曲（去皮层状态）">
              异常屈曲（去皮层状态）
            </el-radio>
            <el-radio label="对疼痛刺激屈曲反应">对疼痛刺激屈曲反应</el-radio>
            <el-radio label="对疼痛刺激定位反应">对疼痛刺激定位反应</el-radio>
            <el-radio label="按吩咐动作">按吩咐动作</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <el-form-item label="REM评分">
        <el-col :span="24">
          <el-col :span="12">
            <el-input v-model="otherScores.vals" placeholder="" />
          </el-col>
        </el-col>
        <el-col :span="2">
          <span>脉搏：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="70 ~ 109">70 ~ 109</el-radio>
            <el-radio label="55 ~ 69">55 ~ 69</el-radio>
            <el-radio label="40 ~ 54">40 ~ 54</el-radio>
            <el-radio label="＜ 40">＜ 40</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>收缩压：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="90 mmHg ~ 129 mmHg">90 mmHg ~ 129 mmHg</el-radio>
            <el-radio label="70 mmHg ~ 89 mmHg">70 mmHg ~ 89 mmHg</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>呼吸：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="12 ~ 24">12 ~ 24</el-radio>
            <el-radio label="10 ~ 11">10 ~ 11</el-radio>
            <el-radio label="6 ~ 9">6 ~ 9</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>GCS：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="＞ 13">＞ 13</el-radio>
            <el-radio label="11 ~ 13">11 ~ 13</el-radio>
            <el-radio label="8 ~ 10">8 ~ 10</el-radio>
            <el-radio label="5 ~ 7">5 ~ 7</el-radio>
            <el-radio label="＜ 5				">＜ 5</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>年龄：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="＜ 45">＜ 45</el-radio>
            <el-radio label="45 ~ 54">45 ~ 54</el-radio>
            <el-radio label="55 ~ 64">55 ~ 64</el-radio>
            <el-radio label="65 ~ 74">65 ~ 74</el-radio>
            <el-radio label="＞ 74">＞ 74</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <span>SpO2：</span>
        </el-col>
        <el-col :span="22">
          <el-radio-group v-model="otherScores.vals">
            <el-radio label="＞ 89">＞ 89</el-radio>
            <el-radio label="86 ~ 89">86 ~ 89</el-radio>
            <el-radio label="75 ~ 85">75 ~ 85</el-radio>
            <el-radio label="＜ 75">＜ 75</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
    </el-form> -->
  </div>
</template>

<script>
import { selectScoreClassAll } from '@/api/green-channel/diagnoses'
import {
  selectPainScore,
  savePainScore,
  selectTriageScore,
  saveTriageScore,
  updateTriageScore
} from '@/api/triage/triage-new'
import Check from '@/components/scoreRow/Check'
import Row from '@/components/scoreRow/Row'
export default {
  name: 'TriageOther',
  props: {
    id: {
      type: Object,
      default: () => {}
    },
    require: {
      type: Array,
      default: () => []
    }
  },
  components: {
    Row,
    Check
  },
  data() {
    return {
      otherScores: {},
      painScore: {},
      painScoreTable: [
        { greater: '>=1', less: '<=3', grade: '轻度疼痛' },
        { greater: '>=4', less: '<=6', grade: '中度疼痛' },
        { greater: '>=7', less: '<=10', grade: '重度疼痛' }
      ],
      required: '',
      scoreModeList: [],
      scoreList: [],
      timer: '',
      flag: true,
      painScoreRules: {
        value: null
      }
    }
  },
  created() {
    this.selectScoreClassAll()
    this.selectPainScore()
    this.setRequire()
  },
  methods: {
    setRequire() {
      if (this.require.length > 0) {
        this.required = this.require[0].value
        if (this.required !== '2') {
          this.painScoreRules.value = [
            { required: true, message: ' ', trigger: 'blur' },
            { min: 1, message: ' ', type: 'number', trigger: 'blur' }
          ]
        } else {
          this.painScoreRules.value = null
        }
      }
    },
    getGradeSpan(item, index) {
      const obj = this.scoreProcess(this.scoreSort([item]))

      this.$set(this.scoreList[index], 'mark', obj.score)
      if (item.scoreConclusionList) {
        this.$set(
          this.scoreList[index],
          'grade',
          this.compareRange(item.scoreConclusionList, obj.score)
        )
      }
    },

    // 收取评分数据
    scoreSort(list) {
      let arr = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].data) {
          arr.push(list[i].data)
        } else {
          arr = arr.concat(this.scoreSort(list[i].scoreClassList))
        }
      }
      return arr
    },
    // 评分数据处理
    scoreProcess(arr) {
      const indexArr = []
      let score = ''
      arr.forEach((el) => {
        if (el.indexOf('||') > 0) {
          indexArr.push(el.split('||')[0])
          if (!score) {
            score = parseInt(el.split('||')[1])
          } else {
            score += parseInt(el.split('||')[1])
          }
        } else {
          indexArr.push(el)
        }
      })
      return {
        index: indexArr.join(','),
        score: score
      }
    },
    // 获取比较分值的结论
    compareRange(list, score) {
      if (list.length === 0) {
        return '未录入描述信息，请联系医院管理员'
      }
      if (!score) {
        return ''
      }
      for (let i = 0; i < list.length; i++) {
        const max = score + list[i].maxcondition + list[i].maximum
        const min = score + list[i].mincondition + list[i].minimum
        if (this.calculator(min) && this.calculator(max)) {
          return list[i].conclusion
        }
      }
      return '所得分值无对应结论，请联系医院管理员'
    },
    painScoreGrade(val) {
      for (let i = 0; i < this.painScoreTable.length; i++) {
        let item = this.painScoreTable[i]
        let greater = this.calculator(val + item.greater)
        let less = this.calculator(val + item.less)
        if (greater && less) {
          this.painScore.score = item.grade
        }
      }
    },
    calculator(str) {
      return new Function('return (' + str + ')')()
    },
    selectPainScore() {
      selectPainScore({ ...this.id, userId: this.$store.getters.userId }).then(
        (res) => {
          if (res.code == 0) {
            this.timer = new Date().getTime()
            if (res.data.length > 0) {
              this.painScore = res.data[0]
              this.painScore.value = Number(this.painScore.value)
            }
          }
        }
      )
    },
    selectTriageScore(index) {
      selectTriageScore(this.id).then((res) => {
        this.scoreList = []
        this.scoreModeList.forEach((el) => {
          let i = 0
          for (i; i < res.data.list.length; i++) {
            if (res.data.list[i].scoreId === el.id) {
              el.grade = res.data.list[i].grade
              el.mark = res.data.list[i].score
              el.score = res.data.list[i]
              el.scoreId = el.id
              el.id = res.data.list[i].id
              this.scoreList.push(JSON.parse(JSON.stringify(el)))
              break
            }
          }
          if (i >= res.data.list.length) {
            el.scoreId = el.id
            el.id = ''
            this.scoreList.push(JSON.parse(JSON.stringify(el)))
          }
        })
        this.scoreSetProcess()
      })
    },
    scoreSetProcess() {
      this.scoreList.forEach((item) => {
        if (item.id) {
          item.data = item.score.index + '||' + item.score.score
          this.scoreSetSort(item.scoreClassList, item.score)
        }
      })
    },
    scoreSetSort(list, score) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].fieldType === 'content') {
          return false
        } else {
          if (!this.scoreSetSort(list[i].scoreClassList, score)) {
            list[i].data = score.index + '||' + score.score
          }
        }
      }
      return true
    },
    selectScoreClassAll() {
      selectScoreClassAll({
        pageNum: 1,
        pageSize: 0,
        greenType: '分诊',
        hospitalId: this.$store.getters.hospitalId,
        type: ''
      }).then((res) => {
        if (res.code === 0) {
          this.scoreModeList = res.data.list
          this.selectTriageScore()
        } else {
          this.$message.error('查询评分模板失败')
        }
      })
    },
    valid() {
      let modFlag = true
      let formFlag = true
      if (this.required == '1') {
        this.scoreList.forEach((item) => {
          if (!item.mark) {
            modFlag = false
          }
        })
        this.$refs.painScoreForm.validate((valid) => {
          formFlag = valid
        })
      }
      if (modFlag && formFlag) {
        this.save()
      } else {
        this.$message.error('请通过验证')
      }
    },
    save() {
      this.savePainScore()
      this.scoreList.forEach((item) => {
        let obj = this.scoreProcess(this.scoreSort([item]))
        if (obj.index) {
          obj.scoreId = item.scoreId
          obj.grade = item.grade
          obj = { ...obj, ...this.id }
          if (item.id) {
            obj.id = item.id
            this.flag = true
            this.updateTriageScore(obj)
          } else {
            this.flag = true
            this.saveTriageScore(obj)
          }
        }
      })
      if (this.flag) {
        this.$message.success('保存成功')
      } else {
        this.$message.error('保存失败')
      }
    },
    savePainScore() {
      savePainScore({
        ...this.painScore,
        ...this.id,
        userId: this.$store.getters.userId
      }).then((res) => {
        if (res.code != 0) {
          this.flag = false
        }
      })
    },
    saveTriageScore(obj) {
      saveTriageScore(obj).then((res) => {
        if (res.code != 0) {
          this.flag = false
        }
      })
    },
    updateTriageScore(obj) {
      updateTriageScore(obj).then((res) => {
        if (res.code != 0) {
          this.flag = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.button-save {
  padding-right: 40px;
  margin-bottom: 20px;
}
.required {
  color: #ff4949;
  margin-right: 4px;
}
.card {
  margin: -1px 45px 0px 35px;
  padding: 10px 20px 0px 10px;
  border-top: 1px dashed #dcdfe6;
  border-radius: 4px;
  &-title {
    margin-bottom: 10px;
    font-size: 15px;
    .content {
      line-height: 40px;
    }
  }
  &-content {
    padding-left: 30px;
    font-size: 14px !important;
    .el-radio {
      min-width: 80px;
    }
    .radio-flex {
      .small-distance {
        margin-right: 0px;
        min-width: 60px !important;
      }
      .el-radio {
        min-width: 110px;
        margin: 0px 20px 20px 0px;
      }
      .small .el-checkbox {
        min-width: 110px;
      }
      .el-checkbox {
        margin: 0px 10px 20px 0px !important;
        min-width: 226.3px;
      }
    }
    .check {
      width: 750px;
    }
    &-result {
      margin: 0px 0px 20px;
    }
    .radio-box .el-radio {
      min-width: 200px;
      padding: 3px 0;
    }
    &-title {
      width: 75px;
      line-height: 32px;
      padding-right: 12px;
    }
    &-subTitle {
      display: flex;
      flex: 0 0 45px;
    }
    .item {
      .row {
        padding-bottom: 20px;
      }
    }
    .result-grade {
      .el-input {
        width: 280px;
      }
    }
    .result-score {
      padding-left: 20px;
      padding-right: 10px;
      .el-input {
        width: 50px;
      }
    }
  }
}
</style>
<style lang="scss">
.triage-other {
  .el-slider__button-wrapper {
    z-index: 0 !important;
  }
}
.require {
  .is-error .el-input__inner {
    border-color: #ff4949;
  }
}
.notRequire {
  .el-form-item.is-error .el-input__inner {
    border-color: #dcdfe6;
  }
}
</style>